package uplift.project;

import java.util.ArrayList;
import java.util.Calendar;

import uplift.project.model.VolunteerEvent;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TimePicker;
import android.widget.Toast;

public class CreateEventActivity extends Activity {

	private EditText eventEditText;
	private EditText locationEditText;
	private EditText dateEditText;
	private EditText startsEditText;
	private EditText endsEditText;
	private EditText descriptionEditText;
	private Spinner categorySpinner;
	
    private int mYear;
    private int mMonth;
    private int mDay;
    
    private int sHour;
    private int sMinute;
    private String sMeridiem;
    
    private int eHour;
    private int eMinute;
    private String eMeridiem;
	
	static final int DATE_DIALOG_ID = 1;
	static final int START_TIME_DIALOG_ID = 2;
	static final int END_TIME_DIALOG_ID = 3;
	
	private Bundle extras;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.create_event);
        
        eventEditText = (EditText) this.findViewById(R.id.editText_event);
        locationEditText = (EditText) this.findViewById(R.id.editText_location);
        dateEditText = (EditText) this.findViewById(R.id.editText_date);
        startsEditText = (EditText) this.findViewById(R.id.editText_starts);
        endsEditText = (EditText) this.findViewById(R.id.editText_ends);
        descriptionEditText = (EditText) this.findViewById(R.id.editText_description);
        
        categorySpinner = (Spinner) findViewById(R.id.spinner_category);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                this, R.array.category_array, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        categorySpinner.setAdapter(adapter);

        dateEditText.setClickable(true);
        dateEditText.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(DATE_DIALOG_ID);
            }
        });
        
        startsEditText.setClickable(true);
        startsEditText.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(START_TIME_DIALOG_ID);
            }
        });
        
        endsEditText.setClickable(true);
        endsEditText.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(END_TIME_DIALOG_ID);
            }
        });
        
        final Calendar c = Calendar.getInstance();
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);
        
        Intent startIntent = this.getIntent();
        extras = startIntent.getExtras();

        if(extras != null){
        	eventEditText.setText(extras.getString("name"));
        	categorySpinner.setSelection(getCategoryPosition(extras.getString("category")));
        	locationEditText.setText(extras.getString("location"));
        	dateEditText.setText(extras.getString("date"));
        	startsEditText.setText(extras.getString("starts"));
        	endsEditText.setText(extras.getString("ends"));
        	descriptionEditText.setText(extras.getString("description"));
        	
        	int[] startTimeArray = convertToTimeArray(extras.getString("starts"));
        	int[] endTimeArray = convertToTimeArray(extras.getString("ends"));
        	sHour = startTimeArray[0];
        	sMinute = startTimeArray[1];
        	eHour = endTimeArray[0];
        	eMinute = endTimeArray[1];
        	
        	String numericDate = getNumericDate(extras.getString("date"));
        	String[] numericDateArray = numericDate.split("-");
        	
            mYear = Integer.parseInt(numericDateArray[2]);
            mMonth = Integer.parseInt(numericDateArray[0]) - 1;
            mDay = Integer.parseInt(numericDateArray[1]);	
        }
        
		// set the action bar to have up-navigation enabled
	    ActionBar actionBar = getActionBar();
	    actionBar.setDisplayHomeAsUpEnabled(true);
	    
    }
    
	@Override
	protected Dialog onCreateDialog(int id) {
	        if (id == DATE_DIALOG_ID) {
                return new DatePickerDialog(this, AlertDialog.THEME_HOLO_DARK,
                        mDateSetListener, mYear, mMonth, mDay);
	        } else if (id == START_TIME_DIALOG_ID) {
		        return new TimePickerDialog(this, AlertDialog.THEME_HOLO_DARK,
		        		sTimeSetListener, 12, 00, false);
	        } else if (id == END_TIME_DIALOG_ID) {
		        return new TimePickerDialog(this, AlertDialog.THEME_HOLO_DARK,
		        		eTimeSetListener, 12, 00, false);
	        }
	        return null;
	}
	
	protected void onPrepareDialog(int id, Dialog dialog) {
	        if (id == DATE_DIALOG_ID) {
                ((DatePickerDialog) dialog).updateDate(mYear, mMonth, mDay);
	        } else if (id == START_TIME_DIALOG_ID) {
	        	((TimePickerDialog) dialog).updateTime(sHour, sMinute);
	        } else if (id == END_TIME_DIALOG_ID) {
	        	((TimePickerDialog) dialog).updateTime(eHour, eMinute);
	        }
	}
	

	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int year, int monthOfYear,
		                int dayOfMonth) {
		        mYear = year;
		        mMonth = monthOfYear;
		        mDay = dayOfMonth;
		        updateDate();
		}
	};
	
	private TimePickerDialog.OnTimeSetListener sTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {			
			if (hourOfDay < 12) {
				sMeridiem = "am";
			} else {
				sMeridiem = "pm";
			}
			
			sHour = hourOfDay;
			sMinute = minute;
			updateStartTime();
		}
	};
	
	private TimePickerDialog.OnTimeSetListener eTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			if (hourOfDay < 12) {
				eMeridiem = "am";
			} else {
				eMeridiem = "pm";
			}
			
			eHour = hourOfDay;
			eMinute = minute;
			updateEndTime();
		}
	};
	
    private void updateDate() {
        dateEditText.setText(
                new StringBuilder()
                // Month is 0 based so add 1
                .append(getMonthName(mMonth)).append(" ")
                .append(mDay).append(", ")
                .append(mYear));
    }
    
    private void updateStartTime() {
        StringBuilder sb = new StringBuilder();
        
        int tempHour = sHour %12;
        
        if (tempHour == 0) {
        	tempHour = 12;
        }
        
        sb.append(tempHour).append(":");
        
        if (sMinute < 10) {
        	sb.append("0");
        }

        sb.append(sMinute).append(sMeridiem);
    	
        startsEditText.setText(sb.toString());
    }
    
    private void updateEndTime() {
        StringBuilder sb = new StringBuilder();
        
        int tempHour = eHour %12;
        
        if (tempHour == 0) {
        	tempHour = 12;
        }
        
        sb.append(tempHour).append(":");
        
        if (eMinute < 10) {
        	sb.append("0");
        }

        sb.append(eMinute).append(eMeridiem);
    	
        endsEditText.setText(sb.toString());
    }

	
    // goes to the preview events screen
    public void previewEvent(View v) {
    	if (!requiredFieldsFilled()) {
    		alertbox("Empty required fields", "You must fill in all of the required fields to preview your event.");
    	} else {
	    	Intent i = new Intent(v.getContext(), PreviewEventActivity.class);
	    	
	    	i.putExtra("name", eventEditText.getText().toString());
	    	i.putExtra("category", categorySpinner.getSelectedItem().toString());
	    	i.putExtra("date", dateEditText.getText().toString());
	    	i.putExtra("location", locationEditText.getText().toString());
	    	i.putExtra("starts", startsEditText.getText().toString());
	    	i.putExtra("ends", endsEditText.getText().toString());
	    	i.putExtra("description", descriptionEditText.getText().toString());
	    	i.putExtra("bundle", extras);
    	
	    	startActivity(i);	
    	}
    }
    
    // Goes to event submission screen
    public void submitEvent(View v) {
    	if (!requiredFieldsFilled()){
    		alertbox("Empty required fields", "You must fill in all of the required fields to submit your event.");
    	} else {
    		confirmBox("Submit Event", "You successfully created event " + eventEditText.getText().toString() + ".", v);
    	}
    }
    
    
    protected void confirmBox(String title, String message, final View v) {
    	new AlertDialog.Builder(new ContextThemeWrapper(this, android.R.style.Theme_Holo_Dialog))
        .setMessage(message)
        .setTitle(title)
        .setPositiveButton("OK",
     		   new DialogInterface.OnClickListener() {
 		           public void onClick(DialogInterface dialog, int whichButton){
 		  			Intent i = new Intent(v.getContext(), UpliftActivity.class);
 					
 					ApplicationData appState = ((ApplicationData)CreateEventActivity.this.getApplicationContext());
 					
 					// This event was being edited after it was submitted previously
 					if (extras != null) {
 						appState.eventsList.removeEvent(extras.getString("name"),
 								extras.getString("category"),
 								extras.getString("location"),
 								extras.getString("date"),
 								extras.getString("starts"),
 								extras.getString("ends"),
 								extras.getString("description"));
 					}
 					
 					VolunteerEvent ve = new VolunteerEvent(eventEditText.getText().toString(),
 															categorySpinner.getSelectedItem().toString(),
 															locationEditText.getText().toString(),
 															dateEditText.getText().toString(),
 															startsEditText.getText().toString(),
 															endsEditText.getText().toString(),
 															descriptionEditText.getText().toString(),
 															true, true);
 					appState.eventsList.addEvent(ve);

 					i.putExtra("name", ((EditText) CreateEventActivity.this.findViewById(R.id.editText_event)).getText().toString());
 					
 					startActivity(i);
 		           }
 		       })
 		.show();
    }
    
    private boolean requiredFieldsFilled() {
    	return (!eventEditText.getText().toString().equals("")) &&
    			(!categorySpinner.getSelectedItem().toString().equals("")) &&
    			(!locationEditText.getText().toString().equals("")) &&
    			(!dateEditText.getText().toString().equals("")) &&
    			(!startsEditText.getText().toString().equals("")) &&
    			(!endsEditText.getText().toString().equals(""));
    }
    
    
    protected void alertbox(String title, String mymessage)
    {
    new AlertDialog.Builder(new ContextThemeWrapper(this, android.R.style.Theme_Holo_Dialog))
       .setMessage(mymessage)
       .setTitle(title)
       .setNeutralButton(android.R.string.ok,
          new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int whichButton){}
          })
       .show();
    }
    
    private String getMonthName(int m) {
    	if (m == 0) {
    		return "January";
    	} else	if (m == 1) {
    		return "February";
    	} else	if (m == 2) {
    		return "March";
    	} else	if (m == 3) {
    		return "April";
    	} else	if (m == 4) {
    		return "May";
    	} else	if (m == 5) {
    		return "June";
    	} else	if (m == 6) {
    		return "July";
    	} else	if (m == 7) {
    		return "August";
    	} else	if (m == 8) {
    		return "September";
    	} else	if (m == 9) {
    		return "October";
    	} else	if (m == 10) {
    		return "November";
    	} else	if (m == 11) {
    		return "December";
    	} else {
    		// Should never actually reach here.
    		return "Imaginary Month";
    	}
    }
    
    
    // handles action item button presses
 	@Override
 	public boolean onOptionsItemSelected(MenuItem item) {
 		if(item.getItemId() == android.R.id.home) {
 			// move up the hierarchy

 			Intent i = new Intent(this.getApplicationContext(), UpliftActivity.class);
 			i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
 			startActivity(i);
 		} else if(item.getItemId() == R.id.menu_home) {
 			// go to Home screen
 			
 			Intent i = new Intent(this.getApplicationContext(), UpliftActivity.class);
 			i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
 			startActivity(i);
 		} else if(item.getItemId() == R.id.menu_my_events) {
 			// go to My Events screen
 			
 			Intent i = new Intent(this.getApplicationContext(), MyEventsTabActivity.class);
 			i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
 			startActivity(i);
 		}
 		return true;
 	}
 	
 	// set up Action Bar
 	@Override
 	public boolean onCreateOptionsMenu(Menu menu) {
 	    MenuInflater inflater = getMenuInflater();
 	    inflater.inflate(R.menu.action_bar, menu);
 	    return true;
 	}
 	
 	private int getCategoryPosition(String catName) {
		if (catName.equals("Elderly")){
			return 1;
		} else if (catName.equals("Food")){
			return 2;
		} else if (catName.equals("Nature")){
			return 3;
		} else if (catName.equals("Animals")){
			return 4;
		} else if (catName.equals("Misc")){
			return 5;
		} else {
			return -1;
		}
	}
 	
    public int[] convertToTimeArray(String time) {
    	String meridiem = time.substring(time.length() - 2, time.length());
    	String[] splitTime = time.substring(0, time.length() - 2).split(":");
    	int[] numTime = new int[] { Integer.parseInt(splitTime[0]), Integer.parseInt(splitTime[1])};
    	
    	if (numTime[0] == 12 && meridiem.equals("am")) {
    		numTime[0] = 0;
    	}
    	
    	if (meridiem.equals("pm")) {
    		numTime[0] += 12;
    	}
    	
    	return numTime;
    }
    
    private String getMonthNumber(String m) {
    	if (m.equals("January")) {
    		return "1";
    	} else	if (m.equals("February")) {
    		return "2";
    	} else	if (m.equals("March")) {
    		return "3";
    	} else	if (m.equals("April")) {
    		return "4";
    	} else	if (m.equals("May")) {
    		return "5";
    	} else	if (m.equals("June")) {
    		return "6";
    	} else	if (m.equals("July")) {
    		return "7";
    	} else	if (m.equals("August")) {
    		return "8";
    	} else	if (m.equals("September")) {
    		return "9";
    	} else	if (m.equals("October")) {
    		return "10";
    	} else	if (m.equals("November")) {
    		return "11";
    	} else	if (m.equals("December")) {
    		return "12";
    	} else {
    		// Should never actually reach here.
    		return "-1";
    	}
    }
    
    
	public String getNumericDate(String date){
		String[] parsed = date.split(" ");
		StringBuilder sb = new StringBuilder();
		
		sb.append(getMonthNumber(parsed[0]));
		sb.append("-");
		sb.append(parsed[1].substring(0, parsed[1].length() - 1));
		sb.append("-");
		sb.append(parsed[2]);
		
		return sb.toString();
	}
 	
}